package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.RedisConstant;
import cn.itcast.entity.Result;

import cn.itcast.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
@Slf4j
@CrossOrigin
@RestController
@RequestMapping(path = "/member")
public class MemberLoginController {
    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 用户登录
     * @param param
     * @return
     */

    @PostMapping(path = "/login")
    public Result memberLogin(@RequestBody Map<String,String> param){
        log.info("进入memberLogin方法了");

        String phone = param.get("phone");
        String validateCode = param.get("validateCode");

        // 判断手机号，验证码是否为空
        if(null == phone || null == validateCode){
            return new Result(false, MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);
        }

        // 从redis中获取验证码
        String redisKey = "LOGIN_" + phone;
        String code = this.redisTemplate.opsForValue().get(redisKey);

        // 校验验证码是否正确
        if(validateCode.equals(code)){
            this.redisTemplate.delete(redisKey);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }

        return new Result(false,MessageConstant.NEED_LOGIN);
    }
}
